// WaterTypeManagement.vue
<template>
    <div>
        <div class="water-type-container">
            <el-select :model-value="modelValue" placeholder="请选择用水类别" style="width: 100%"
                @change="$emit('update:modelValue', $event)" clearable>
                <el-option v-for="type in waterTypeStore.waterTypes" :key="type.id" :label="type.name"
                    :value="type.id" />
            </el-select>
            <el-button type="primary" @click="showDialog = true" class="ml-2">
                管理类别
            </el-button>
        </div>

        <!-- 用水类别管理对话框 -->
        <el-dialog v-model="showDialog" title="用水类别管理" width="500px" destroy-on-close>
            <div class="water-type-management" v-loading="loading">
                <div class="type-list">
                    <div v-for="type in waterTypeStore.waterTypes" :key="type.id" class="type-item">
                        <span>{{ type.name }}</span>
                        <el-button type="danger" size="small" @click="handleDeleteType(type)">
                            删除
                        </el-button>
                    </div>
                </div>
                <div class="add-type-form">
                    <el-input v-model="newTypeName" placeholder="请输入新类别名称" class="mr-2" />
                    <el-button type="primary" @click="addWaterType" :disabled="!newTypeName.trim()">
                        添加
                    </el-button>
                </div>
            </div>
            <template #footer>
                <el-button @click="showDialog = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { useWaterTypeStore } from '@/stores/waterType'
import { addWaterTypeApi, deleteTypeApi } from '@/api/extendedType';
let loading = ref(false)
const props = defineProps({
    modelValue: {
        type: Number,
        required: false, // 改为 false，允许为空
        default: null    // 添加默认值 null
    }
})

const emit = defineEmits(['update:modelValue'])

// 使用 water type store
const waterTypeStore = useWaterTypeStore()

// 本地状态
const showDialog = ref(false)
const newTypeName = ref('')

// 自动获取水类型数据
watchEffect(() => {
    if (!waterTypeStore.waterTypes.length) {
        waterTypeStore.getWaterTypes()
    }
})

// 添加新的用水类别
const addWaterType = async () => {
    if (!newTypeName.value.trim()) {
        ElMessage.warning('类别名称不能为空')
        return
    }

    // 检查类别名称是否重复
    if (waterTypeStore.waterTypes.some(type => type.name === newTypeName.value.trim())) {
        ElMessage.warning('类别名称已存在')
        return
    }

    const newType = {
        name: newTypeName.value.trim(),
    }
    try {
        loading.value = true
        await addWaterTypeApi(newType)
        ElMessage.success('添加成功')
    } catch (error) {
        ElMessage.error(error.message || '添加失败')
    } finally {
        loading.value = false
        waterTypeStore.getWaterTypes()
        newTypeName.value = ''
    }
}


// 处理删除类型
const handleDeleteType = (type) => {
    ElMessageBox.confirm(
        `确定要删除类别"${type.name}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        deleteWaterType(type)
    }).catch(() => { })
}

// 删除用水类别
const deleteWaterType = async (type) => {
    try {
        loading.value = true
        await deleteTypeApi({ id: '' + type.id })
        ElMessage.success('删除成功')
    } catch (error) {
        console.error(error)
        ElMessage.error(error.message || '删除失败')
    } finally {
        loading.value = false
        waterTypeStore.getWaterTypes()
    }
}
</script>

<style scoped>
.water-type-container {
    min-width: 20rem;
    display: flex;
    align-items: center;
    gap: 10px;
}

.water-type-management {
    padding: 10px;
}

.type-list {
    margin-bottom: 20px;
    max-height: 300px;
    overflow-y: auto;
}

.type-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px;
    border-bottom: 1px solid #eee;
}

.type-item:last-child {
    border-bottom: none;
}

.add-type-form {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}

.ml-2 {
    margin-left: 8px;
}

.mr-2 {
    margin-right: 8px;
}

/* 确保下拉框和输入框在容器中的合适宽度 */
.water-type-container .el-select {
    flex: 1;
}

.water-type-container .el-button {
    flex-shrink: 0;
}

/* 类别管理对话框中的样式 */
.add-type-form .el-input {
    flex: 1;
}

.type-item .el-button {
    margin-left: 10px;
}
</style>